# Definition for a binary tree node.
from typing import List, Optional


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        if len(preorder) == 0 or len(inorder) == 0:
            return None

        val = preorder[0]
        idx = inorder.index(val)
        in_left = inorder[0: idx]
        in_right = inorder[idx + 1:]
        pre_left = preorder[1:len(in_left) + 1]
        pre_right = preorder[1 + len(pre_left):]
        # print(pre_left, pre_right)
        # print(in_left, in_right)

        node = TreeNode(val=val,
                        left=self.buildTree(pre_left, in_left),
                        right=self.buildTree(pre_right, in_right))
        return node
